package org.rency.mq.activemq.listener.factory;

import org.apache.activemq.command.ActiveMQBytesMessage;
import org.rency.mq.activemq.exception.MessageHandleException;
import org.rency.mq.activemq.listener.handler.MessageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import javax.jms.*;

public abstract class AbstractMessageListener implements MessageListener {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private MessageHandler messageHandler;
	
	public void onMessage(Message message) {
		Assert.notNull(messageHandler, "MessageHandler cannot be null.");
		logger.debug("The handler is: {}.",messageHandler.getClass());
		
		Object request = null;
		if (message instanceof ObjectMessage) {
			ObjectMessage objMessage = (ObjectMessage) message;
			try {
				request = objMessage.getObject();
			} catch (JMSException e) {
				logger.error("Listenning message error, Message: {}.",message, e);
			}
		}else if(message instanceof TextMessage){
			TextMessage textMessage = (TextMessage)message;
			
			try {
				request = textMessage.getText();
			} catch (JMSException e) {
				logger.error("Listenning message error, Message: {}.",message, e);
			}
		}else if(message instanceof ActiveMQBytesMessage){
		    ActiveMQBytesMessage bytesMessage = (ActiveMQBytesMessage)message;
		    request = new String(bytesMessage.getContent().data);
		}else{
			logger.error("Incorrect message type, Message: {}.",message);
			throw new MessageHandleException("Incorrect message type, Message: "+message);
		}

		logger.info("Listen on message: {}.",request);
		if(request == null) {
			return;
		}
		handleRequest(request);
	}

	public abstract void handleRequest(Object request);

	public MessageHandler getMessageHandler() {
		return messageHandler;
	}

	public void setMessageHandler(MessageHandler messageHandler) {
		this.messageHandler = messageHandler;
	}

    public Logger getLogger() {
        return logger;
    }

}
